package com.example.demo.service;

/**
 * Description: <br/>
 *
 * @author liulonglong<br                                                                                                                                                                                                                                                               />;
 * @taskId <br/>
 * @Date 2019/5/28 14:51
 * @Version 1.0
 */

import java.io.IOException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class SmsService {

    @Autowired
    private RestTemplate restTemplate;

    public void sendMessage(String phone) {

        String url = "https://vip.veesing.com/smsApi/verifyCode";
        // 验证码变量(随机数)
        Integer num = (int) ((Math.random() * 9 + 1) * 1000);
        String variables = num.toString();
        JSONObject json = new JSONObject();
        json.put("appId", "3R49QUP15UKB");
        json.put("appKey", "K5U4G7CIDI1NQCFX");
        json.put("phone", phone);
        json.put("templateId", "369");
        json.put("variables", variables + ";" + "测试");
        HttpHeaders headers = new HttpHeaders();
        headers.add("ContentType", "application/x-www-form-urlencoded;charset=utf-8");
        HttpEntity<String> postBody = new HttpEntity<>(json.toString(), headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, postBody, String.class);
        String body = responseEntity.getBody();
        try {
            JSONObject resp = JSON.parseObject(body);
            if (resp.getString("returnStatus").equals("1")) {
                log.info("短信发送成功！");
            } else {
                log.info("短信发送失败！");
            }
        } catch (Exception e) {
            log.error("Json Parse Failed!");
        }
    }
}
